﻿// Stickers
// An example app demonstrating cloud native .NET apps
// Written by daxnet (Sunny Chen)
// MIT License
// 2024

using System.Net;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.WebAssembly.Authentication;

namespace Stickers.Web.Utilities;

public class StickersMessageHandler : AuthorizationMessageHandler
{
    private readonly NavigationManager _navigationManager;
    
    public StickersMessageHandler(IAccessTokenProvider provider, NavigationManager navigation) : base(provider,
        navigation)
    {
        ConfigureHandler(["http://localhost:5141", "http://localhost:8080/api"]);
        _navigationManager = navigation;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        try
        {
            var responseMessage = await base.SendAsync(request, cancellationToken);
            if (responseMessage.StatusCode == HttpStatusCode.Forbidden)
            {
                _navigationManager.NavigateTo("/forbidden");
            }
    
            return responseMessage;
        }
        catch (AccessTokenNotAvailableException ex)
        {
            ex.Redirect();
            return new HttpResponseMessage();
        }
    }
}